import json
import os
import re

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.utils import timezone
from django.utils.timezone import now
from django.views import View

import constants
from apps.company.models import Company
from apps.position.models import ReceiveResume, Position
from apps.resume.models import UserBaseInfo, ExpectWork, ProjectExp, EduBkGround, SelfDesc, ProductionShow, WorkExp, \
    UserResume
from apps.resume.utils import query_resume
from lagouwang.settings import STATICFILES_DIRS


class UserResumeView(LoginRequiredMixin, View):
    """用户简历中心"""

    def get(self, request):
        user = request.user

        user_resume = query_resume(user.id)
        try:
            resume = UserResume.objects.get(user_id=user.id)
        except:
            resume = None
        # 查询该用户有没有公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            company = None

        context = {
            'user': user,  # 用户
            'resume': resume,  # 用户简历
            "base_info": user_resume.get('base_info'),  # 用户基本信息
            "expect_work": user_resume.get('expect_work'),  # 用户期待工作
            "work_exp": user_resume.get('work_exp'),  # 用户工作经历
            "pro_exp": user_resume.get('pro_exp'),  # 用户项目经验
            "edu_bk": user_resume.get('edu_bk'),  # 用户教育背景
            "self_desc": user_resume.get('self_desc'),  # 用户自我描述
            "production": user_resume.get('production'),  # 用户作品展示
            "company": company,  # 用户作品展示
        }
        return render(request, 'jianli.html', context)


class UpdateBasicInfoView(LoginRequiredMixin, View):
    """修改基本信息"""

    def post(self, request):
        user = request.user
        real_name = request.POST.get('name')
        gender = request.POST.get('gender')
        education = request.POST.get('topDegree')
        edu_age = request.POST.get('workyear')
        b_mobile = request.POST.get('tel')
        b_email = request.POST.get('email')
        cur_status = request.POST.get('currentState')
        head_image = request.FILES.get('headPic')

        # 头像设置
        path = None
        if head_image:
            path = os.path.join(STATICFILES_DIRS[0], 'upload_images/' + head_image.name)
            if head_image.multiple_chunks():
                file_yield = head_image.chunks()
                with open(path, 'wb') as f:
                    for buf in file_yield:
                        f.write(buf)
                    else:
                        print('大文件上传完毕')
            else:
                with open(path, 'wb') as f:
                    f.write(head_image.read())
                print('小文件上传完毕')
        if path == None:
            if gender == '男':
                header_image = 'upload_images/' + 'default_male.jpg'
            else:
                header_image = 'upload_images/' + 'default_female.jpg'
        else:
            header_image = 'upload_images/' + head_image.name
        # 校验参数
        if not all([real_name, gender, education, edu_age, cur_status]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整信息后提交'})

        if gender not in ['男', '女']:
            return http.JsonResponse({'errno': constants.GENDERERROR, 'errmsg': '性别错误'})

        if b_mobile:
            if not re.match('^1[3-9]\d{9}', b_mobile):
                return http.JsonResponse({'errno': constants.MOBILEERROR, 'errmsg': '手机格式不正确'})

        if b_email:
            if not re.match('^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', b_email):
                return http.JsonResponse({'errno': constants.EMAILERROR, 'errmsg': '邮箱格式错误'})
        # 添加并保存到数据库
        print("开始修改")
        try:
            print("查询是否存在用户基本信息")
            # 判断该用户是否有基本信息
            try:
                user_base_info = UserBaseInfo.objects.get(user_id=user.id)
            except:
                user_base_info = None
            if user_base_info != None:
                print('有这个对象，开始修改')
                user_base_info = UserBaseInfo.objects.update(
                    real_name=real_name,
                    cur_status=cur_status,
                    education=education,
                    eduage=edu_age,
                    b_email=b_email,
                    b_mobile=b_mobile,
                    gender=gender,
                    head_image=header_image,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                print("没有该用户基本信息对象，创建")
                user_base_info = UserBaseInfo.objects.create(
                    real_name=real_name,
                    cur_status=cur_status,
                    education=education,
                    eduage=edu_age,
                    b_email=b_email,
                    b_mobile=b_mobile,
                    gender=gender,
                    head_image=header_image,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({"errno": constants.DBERROR, 'errmsg': '系统繁忙，请稍后再试'})

        return http.JsonResponse({"errno": constants.OK, 'errmsg': '修改成功'})


class UpdateExpectWorkView(LoginRequiredMixin, View):
    def post(self, request):
        user = request.user
        json_data = json.loads(request.body.decode())
        city = json_data.get('city')
        work_kind = json_data.get('work_kind')
        position = json_data.get('position')
        salary = json_data.get('salary')

        # 校验参数
        if not all([city, work_kind, position, salary]):
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '请填写完整信息'})

        if work_kind not in ['全职', '兼职', '实习']:
            return http.JsonResponse({"errno": constants.WORKCHOICEERROR, 'errmsg': '异常'})

        # 保存到数据库
        try:
            try:
                user_expect_work = ExpectWork.objects.get(user_id=user.id)
            except:
                user_expect_work = None

            if user_expect_work != None:
                user_expect_work = ExpectWork.objects.update(
                    city=city,
                    work_kind=work_kind,
                    position=position,
                    salary=salary,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                user_expect_work = ExpectWork.objects.create(
                    city=city,
                    work_kind=work_kind,
                    position=position,
                    salary=salary,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class UpdateWorkExpView(LoginRequiredMixin, View):
    """更新工作经历"""

    def post(self, request):
        user = request.user

        json_data = json.loads(request.body.decode())
        company_name = json_data.get("company_name")
        job_name = json_data.get("job_name")
        startyear = json_data.get("startyear")
        startmonth = json_data.get("startmonth")
        endyear = json_data.get("endyear")
        endmonth = json_data.get("endmonth")

        # 校验参数
        if not all([company_name, job_name, startyear, startmonth, endyear, endmonth]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整信息'})

        start_time = startyear + '年' + startmonth + '月'

        if endyear == '至今':
            end_time = endyear
        else:
            end_time = endyear + '年' + endmonth + '月'

        # 保存到数据库
        try:
            try:
                user_work_exp = WorkExp.objects.get(user_id=user.id)
            except:
                user_work_exp = None

            if user_work_exp != None:
                user_work_exp = WorkExp.objects.update(
                    company_name=company_name,
                    job_name=job_name,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                user_work_exp = WorkExp.objects.create(
                    company_name=company_name,
                    job_name=job_name,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '保存成功'})


class UpdateProjectExpView(LoginRequiredMixin, View):
    """项目经验"""

    def post(self, request):
        # 当前用户
        user = request.user

        # 获取参数
        json_data = json.loads(request.body.decode())
        pro_name = json_data.get("pro_name")  # 项目名称
        post_name = json_data.get("post_name")  # 担当职位
        pro_start_year = json_data.get("pro_start_year")  # 项目开启时间
        pro_start_month = json_data.get("pro_start_month")
        pro_year_end = json_data.get("pro_year_end")  # 项目结束时间
        pro_month_end = json_data.get("pro_month_end")
        content = json_data.get("content")  # 项目描述

        # 校验参数
        if not all([pro_name, post_name, pro_start_year, pro_start_month, pro_year_end, pro_month_end, content]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整信息'})

        start_time = pro_start_year + '年' + pro_start_month + '月'
        if pro_year_end == '至今':
            end_time = pro_year_end
        else:
            end_time = pro_year_end + '年' + pro_month_end + '月'

        # 保存到数据库
        try:
            try:
                pro_exp = ProjectExp.objects.get(user_id=user.id)
            except:
                pro_exp = None

            if pro_exp != None:
                pro_exp = ProjectExp.objects.update(
                    pro_name=pro_name,
                    post_name=post_name,
                    content=content,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                pro_exp = ProjectExp.objects.create(
                    pro_name=pro_name,
                    post_name=post_name,
                    content=content,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class UpdateEduBkView(LoginRequiredMixin, View):
    """修改用户教育背景"""

    def post(self, request):

        user = request.user

        # 获取参数
        school_name = request.POST.get('school_name')
        education = request.POST.get('degree')
        major = request.POST.get('pro_name')
        start_year = request.POST.get('schoolYearStart')
        end_year = request.POST.get('schoolYearEnd')

        # 校验参数
        if not all([school_name, education, major, start_year, end_year]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整信息'})

        start_time = start_year + '年'
        end_time = end_year + '年'

        # 保存到数据库
        try:
            try:
                edu_bk = EduBkGround.objects.get(user_id=user.id)
            except:
                edu_bk = None

            if edu_bk != None:
                edu_bk = EduBkGround.objects.update(
                    school_name=school_name,
                    education=education,
                    major=major,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                edu_bk = EduBkGround.objects.create(
                    school_name=school_name,
                    education=education,
                    major=major,
                    start_time=start_time,
                    end_time=end_time,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class UpdateSelfDescView(LoginRequiredMixin, View):
    """修改自我描述"""

    def post(self, request):
        user = request.user

        content = request.POST.get('selfDescription')

        if not content:
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请输入描述内容'})
        # 保存到数据库
        try:
            try:
                self_desc = SelfDesc.objects.get(user_id=user.id)
            except:
                self_desc = None

            if self_desc != None:
                self_desc = SelfDesc.objects.update(
                    content=content,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                self_desc = SelfDesc.objects.create(
                    content=content,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class UpdateShowProductView(LoginRequiredMixin, View):
    """修改作品展示"""

    def post(self, request):

        user = request.user
        url = request.POST.get('workLink')
        explain = request.POST.get('workDescription')

        if not all([url, explain]):
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '请填写完整信息'})
            # 保存到数据库
        try:
            try:
                works_show = ProductionShow.objects.get(user_id=user.id)
            except:
                works_show = None

            if works_show != None:
                works_show = ProductionShow.objects.update(
                    production_url=url,
                    explain=explain,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                works_show = ProductionShow.objects.create(
                    production_url=url,
                    explain=explain,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class UpdateResumeTitle(LoginRequiredMixin, View):
    """个人简历标题修改"""

    def post(self, request):
        user = request.user

        user_resume = query_resume(user.id)
        user_basic = user_resume.get('base_info')
        expect_work = user_resume.get('expect_work')
        work_exp = user_resume.get('work_exp')
        projectexp = user_resume.get('pro_exp')
        edu_bk = user_resume.get('edu_bk')
        self_desc = user_resume.get('self_desc')
        worksshow = user_resume.get('production')

        if not all([user_resume, user_basic, expect_work, work_exp, projectexp, edu_bk, self_desc, worksshow]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请先完善简历信息'})
        title = request.POST.get('resumeName')

        if not title:
            return http.JsonResponse({'errno': constants.TITLEERROR, 'errmsg': '请填写简历标题'})

        try:
            try:
                resume = UserResume.objects.get(user_id=user.id)
            except:
                resume = None

            if resume != None:
                resume = UserResume.objects.update(
                    title=title,
                    user_basic=user_basic,
                    expect_work=expect_work,
                    work_exp=work_exp,
                    projectexp=projectexp,
                    edubk=edu_bk,
                    selfdesc=self_desc,
                    worksshow=worksshow,
                    user=user,
                    update_time=now(),
                )
            else:
                resume = UserResume.objects.create(
                    title=title,
                    user_basic=user_basic,
                    expect_work=expect_work,
                    work_exp=work_exp,
                    projectexp=projectexp,
                    edubk=edu_bk,
                    selfdesc=self_desc,
                    worksshow=worksshow,
                    user=user,
                    update_time=now(),
                )
        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '修改失败'})

        return http.JsonResponse({'errno': constants.OK, 'errmsg': '修改成功'})


class SendResumeView(LoginRequiredMixin, View):
    """投简历"""

    def post(self, request):
        user = request.user
        json_data = json.loads(request.body.decode())
        pos_id = json_data.get('pos_id')

        if not pos_id:
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': "投递简历失败,请稍后再试"})

        try:
            resume = UserResume.objects.get(user_id=user.id)
        except:
            return http.JsonResponse({"errno": constants.INFO_MISSING, "errmsg": "缺少简历信息"})

        # 查询该用户是否是企业用户
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            company = None

        if company != None:
            return http.JsonResponse({'errno': constants.DBERROR, "errmsg": "企业用户不可投递简历"})

        # 正式发起投递
        try:
            # 查询是否存在该投递的对象
            try:
                sendresume = ReceiveResume.objects.get(position_id=pos_id, resume_id=resume.id)
            except:
                sendresume = None

            if sendresume != None:
                return http.JsonResponse({"errno": constants.DBERROR, "errmsg": "已投递过该职位"})
            else:
                sendresume = ReceiveResume.objects.create(
                    resume=resume,
                    position_id=pos_id,
                    status=1,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                    create_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
        except:
            http.JsonResponse({"errno": constants.DBERROR, 'errmsg': "投递失败，请稍后再试"})

        return http.JsonResponse({"errno": constants.OK, 'errmsg': "投递成功"})


class WaitingResumeView(LoginRequiredMixin, View):
    """待处理简历"""

    def get(self, request):
        user = request.user

        # 查询该用户的公司
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, "common/404.html")

        # 查询该公司发布的职位
        try:
            position = Position.objects.filter(company_id=company.id)
            if position.count() == 0:
                position = None
        except:
            position = None
        pos_id_list = []
        if position != None:
            for pos in position:
                pos_id_list.append(pos.id)

        # 查询待定简历
        try:
            rec_resumes = ReceiveResume.objects.filter(position_id__in=pos_id_list, status=1)
        except:
            rec_resumes = None
        print(rec_resumes)
        context = {
            "user": user,
            "company": company,  # 用户的公司
            "position": position,  # 公司发布的职位
            "rec_resumes": rec_resumes,  # 收到的简历
        }
        return render(request, "canInterviewResumes.html", context)


class ShowResumeView(LoginRequiredMixin, View):
    """展示用户简历"""

    def get(self, request, resume_id):
        # 查询该简历是哪个用户的
        try:
            resume = UserResume.objects.get(id=resume_id)
        except:
            return render(request, "common/404.html")

        context = {
            "resume": resume,  # 简历
        }

        return render(request, "preview.html", context)
